<template>
  <div class="course-list-container">
    <!-- 顶部导航组件 -->
    <Header />

    <!-- 筛选区域 -->
    <div class="filter-section">
      <!-- 课程分类筛选 -->
      <div class="filter-item">
        <span class="label">课程分类：</span>
        <div class="options">
          <a href="#"
             v-for="category in categories"
             :key="category.id"
             :class="{ active: selectedCategory === category.id }"
             @click.prevent="handleCategoryClick(category.id, category.name)">
            {{ category.name }}
          </a>
        </div>
      </div>

      <!-- 排序方式筛选 -->
      <div class="filter-item">
        <span class="label">排序方式：</span>
        <div class="options">
          <a href="#"
             v-for="sort in ['默认排序', '最新', '最热', '价格']"
             :key="sort"
             :class="{ active: selectedSort === sort }"
             @click.prevent="handleSortClick(sort)">
            {{ sort }}
          </a>
        </div>
      </div>

      <!-- 价格区间筛选 -->
      <div class="filter-item">
        <span class="label">价格区间：</span>
        <div class="options">
          <a href="#"
             v-for="price in ['全部', '免费', '付费']"
             :key="price"
             :class="{ active: selectedPrice === price }"
             @click.prevent="handlePriceClick(price)">
            {{ price }}
          </a>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="course-grid">
      <div v-for="course in courses" :key="course.id" class="course-card" @click="handleCourseClick(course.id)">
        <!-- 课程卡片内容 -->
        <img :src="course.course_img" :alt="course.name">
        <div class="course-info" >
          <h3>{{ course.name }}</h3>
          <p class="description">{{ course.brief }}</p>
          <!-- 讲师信息 -->
          <div class="instructor">
            <span class="name">{{ course.teacher.name }}</span>
            <span class="title">{{ course.teacher.title }}</span>
          </div>
          <!-- 课程统计信息 -->
          <div class="stats">
            <span>{{ course.students }}人学习</span>
            <span>{{ course.lessons }}课时</span>
          </div>
          <!-- 价格和购买按钮 -->
          <div class="price-action">
            <div class="price-info">
              <span class="price" v-if="course.course_type === 2">¥{{ course.price }}</span>
              <span class="original-price" v-if="course.course_type === 2">¥{{ course.original_price }}</span>
              <span class="price free" v-else>免费</span>
            </div>
            <button class="add-to-cart">加入购物车</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="total > 0">
      <a href="#" class="page-btn" @click.prevent="handlePageChange(1)">首页</a>
      <a href="#" class="page-btn" @click.prevent="handlePageChange(currentPage - 1)"
         :class="{ disabled: currentPage === 1 }">上一页</a>
      <span class="page-number">{{ currentPage }} / {{ totalPages }}</span>
      <a href="#" class="page-btn" @click.prevent="handlePageChange(currentPage + 1)"
         :class="{ disabled: currentPage === totalPages }">下一页</a>
      <a href="#" class="page-btn" @click.prevent="handlePageChange(totalPages)">末页</a>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import Header from '../components/Header.vue'

const route = useRoute()
const router = useRouter()

// 筛选条件状态
const selectedCategory = ref('全部')
const selectedSort = ref('默认排序')
const selectedPrice = ref('全部')

// 课程分类数据
const categories = ref([])

// 课程列表数据
const courses = ref([])

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const totalPages = ref(1)
const keyword = ref('')

/**
 * 获取课程列表数据
 * 根据当前的筛选条件、分页参数和路由参数获取课程数据
 */
const fetchCourses = async () => {
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 添加导航名称或分类ID查询参数
    if (route.query.nav_name) {
      params.nav_name = route.query.nav_name
    }
    if (route.query.categoryId) {
      params.categoryId = route.query.categoryId
    }

    params.keyword = keyword.value

    // 发起API请求
    const response = await axios.get('http://127.0.0.1:8000/api/list/', { params })
    if (response.data.code === 1) {
      courses.value = response.data.data.results
      total.value = response.data.data.count
      totalPages.value = Math.ceil(total.value / pageSize.value)
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

/**
 * 获取课程分类数据
 */
const fetchCategories = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8000/api/behindcategory/')
    if (response.data.code === 1) {
      // 添加"全部"选项
      const allCategories = [
        { id: 0, name: '全部', level: 1 },
        ...response.data.data.filter(item => item.level === 1)
      ]
      categories.value = allCategories
    }
  } catch (error) {
    console.error('获取课程分类失败:', error)
  }
}

/**
 * 处理分类点击事件
 * @param {number} categoryId - 选中的分类ID
 * @param {string} categoryName - 选中的分类名称
 */
const handleCategoryClick = (categoryId, categoryName) => {
  selectedCategory.value = categoryId
  currentPage.value = 1
  router.push({
    query: { ...route.query, categoryId }
  })
}

/**
 * 处理排序方式点击事件
 * @param {string} sort - 选中的排序方式
 */
const handleSortClick = (sort) => {
  selectedSort.value = sort
  currentPage.value = 1

  const params = {
    page: currentPage.value,
    page_size: pageSize.value
  }

  if (route.query.nav_name){
    params.nav_name = route.query.nav_name
  }

  if (route.query.categoryId){
    params.categoryId = route.query.categoryId
  }

  if (sort === '最新'){
    params.sorted_num = 1
  }else if (sort === '最热'){
    params.sorted_num = 2
  }else if (sort === '价格'){
    params.sorted_num = 3
  }else {
    params.sorted_num = ''
  }

  axios.get(`http://127.0.0.1:8000/api/list/`,{params}).then(res=>{
    if (res.data.code === 1){
      courses.value = res.data.data.results
      total.value = res.data.data.count
      totalPages.value = Math.ceil(total.value / pageSize.value)
    }
  })

}

/**
 * 处理价格筛选点击事件
 * @param {string} price - 选中的价格区间
 */
const handlePriceClick = (price) => {
  selectedPrice.value = price
  currentPage.value = 1

  const params = {
    page: currentPage.value,
    page_size: pageSize.value
  }

  if (route.query.nav_name){
    params.nav_name = route.query.nav_name
  }

  if (route.query.categoryId){
    params.categoryId = route.query.categoryId
  }

  if (selectedCategory.value === '最新'){
    params.sorted_num = 1
  }else if (selectedCategory.value === '最热'){
    params.sorted_num = 2
  }else if (selectedCategory.value === '价格'){
    params.sorted_num = 3
  }else {
    params.sorted_num = ''
  }


  if (price === '免费'){
    params.price_range = 1
  }else if (price === '付费'){
    params.price_range = 2
  }else {
    params.price_range = ''
  }

  axios.get(`http://127.0.0.1:8000/api/list/`,{params}).then(res=>{
    if (res.data.code === 1){
      courses.value = res.data.data.results
      total.value = res.data.data.count
      totalPages.value = Math.ceil(total.value / pageSize.value)
    }
  })

}

// 页面详情跳转
function handleCourseClick(courseId){
  router.push('/detail/'+courseId)
}





/**
 * 处理分页切换事件
 * @param {number} page - 目标页码
 */
const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value || page === currentPage.value) return
  currentPage.value = page
  fetchCourses()
}

// 监听路由参数变化
watch([() => route.query.nav_name, () => route.query.categoryId], ([newNavName, newCategoryId]) => {
  if (newNavName) {
    selectedCategory.value = newCategoryId
  }
  currentPage.value = 1
  fetchCourses()
}, { immediate: true })

// 组件挂载时初始化数据
onMounted(() => {
  if (route.query.nav_name) {
    // selectedCategory.value = route.query.nav_name
    selectedCategory.value = route.query.categoryId
  }

  if(route.query.keyword){
    keyword.value = route.query.keyword
  }

  fetchCategories()
  fetchCourses()
})
</script>

<style scoped>
/* 容器样式 */
.course-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 筛选区域样式 */
.filter-section {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  line-height: 32px;
}

.filter-item:last-child {
  margin-bottom: 0;
}

/* 筛选标签样式 */
.label {
  color: #666;
  margin-right: 10px;
  min-width: 70px;
  text-align: right;
  flex-shrink: 0;
}

/* 选项容器样式 */
.options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

/* 选项链接样式 */
.options a {
  color: #333;
  text-decoration: none;
  margin-right: 20px;
  padding: 2px 8px;
  border-radius: 2px;
  margin-bottom: 5px;
}

.options a:hover {
  color: #ff6b00;
}

.options a.active {
  color: #ff6b00;
  font-weight: 500;
}

/* 课程网格布局 */
.course-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

/* 课程卡片样式 */
.course-card {
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  transition: transform 0.3s;
  width: 100%;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 课程图片样式 */
.course-card img {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

/* 课程信息样式 */
.course-info {
  padding: 15px;
}

.course-info h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
}

.description {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  height: 40px;
  overflow: hidden;
}

/* 讲师信息样式 */
.instructor {
  margin-bottom: 10px;
}

.instructor .name {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}

.instructor .title {
  color: #666;
  font-size: 12px;
}

/* 统计信息样式 */
.stats {
  color: #999;
  font-size: 12px;
  margin-bottom: 10px;
}

.stats span {
  margin-right: 15px;
}

/* 价格和操作区域样式 */
.price-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  flex-direction: column;
}

.price {
  color: #ff6b00;
  font-size: 18px;
  font-weight: bold;
}

.original-price {
  color: #999;
  font-size: 12px;
  text-decoration: line-through;
}

.price.free {
  color: #52c41a;
}

/* 加入购物车按钮样式 */
.add-to-cart {
  background: #ff6b00;
  color: white;
  border: none;
  padding: 6px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.add-to-cart:hover {
  background: #ff8533;
}

/* 分页控件样式 */
.pagination {
  text-align: center;
  margin-top: 20px;
}

.page-btn {
  display: inline-block;
  padding: 5px 10px;
  margin: 0 5px;
  color: #666;
  text-decoration: none;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.page-btn:hover {
  color: #ff6b00;
  border-color: #ff6b00;
}

.page-number {
  margin: 0 10px;
  color: #666;
}

.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.disabled:hover {
  color: #666;
  border-color: #d9d9d9;
}
</style>